package com.liang.gulimall.order.web;

import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liang.gulimall.order.config.AlipayTemplate;
import com.liang.gulimall.order.entity.OrderEntity;
import com.liang.gulimall.order.entity.OrderItemEntity;
import com.liang.gulimall.order.service.OrderItemService;
import com.liang.gulimall.order.service.OrderService;
import com.liang.gulimall.order.vo.PayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.List;

@Controller
public class PayController {
    @Autowired
    AlipayTemplate alipayTemplate;
    @Autowired
    OrderService orderService;
    @Autowired
    OrderItemService orderItemService;

    @ResponseBody
    @GetMapping(value = "/aliPayOrder",produces = "text/html")
    public String aliPayOrder(@RequestParam("orderSn") String orderSn){
        PayVo payVo = new PayVo();
        payVo.setOut_trade_no(orderSn);
        OrderEntity orderEntity = orderService.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        payVo.setTotal_amount(orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP).toString());
        List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        StringBuilder subject=new StringBuilder();
        for (OrderItemEntity itemEntity : itemEntities) {
            subject.append(itemEntity.getSkuName()+";");
        }
        String s = subject.toString();
        String substring = s.substring(0, s.length() - 1);
        payVo.setSubject(substring);
        String pay = null;
        try {
            pay = alipayTemplate.pay(payVo);//返回的是一个页面
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return pay;
    }
}
